import { promises as fs, Dirent } from 'fs';
import * as child_process from 'child_process';
import config from './config';
import path = require('path');
import getFilesPath from './files';
import translate from './translate';
import { collectDirsPathByFilesPath, mkdirByDirsPath } from './dirs';
import { inputPathToOutputPath } from './path';

const { outputDirPath } = config;

async function main() {
  await fs.rmdir(outputDirPath, { recursive: true })
  
  const [filesPath, ignoreDirsPath, ignoreFilesPath] = await getFilesPath();
  const outputDirsPath = collectDirsPathByFilesPath(filesPath);
  
  await mkdirByDirsPath(outputDirsPath);
  await translateFiles(filesPath);

  // copy 忽略的文件
  await copyIgnoreDirs(ignoreDirsPath, inputPathToOutputPath);
  await copyIgnoreFiles(ignoreFilesPath, inputPathToOutputPath);
}

async function translateFiles(filesPath: string[]) {
  for await (const filePath of filesPath) {
    const fileContent = await fs.readFile(filePath, { encoding: 'utf-8' });
    const translatedContent = await translate(fileContent);
    
    const outputPath = inputPathToOutputPath(filePath);
    await fs.writeFile(outputPath, translatedContent);
    console.log('translated success: ', outputPath);
  }
}

async function copyIgnoreDirs(dirs: string[], transformPathFunc: (path: string) => string) {
  for await (const dirPath of dirs) {
    if (path.basename(dirPath) === '.git') continue;
    const outputDirPath = transformPathFunc(dirPath);
    child_process.spawn('cp', ['-r', `'${dirPath}'`, `'${outputDirPath}'`], { shell: 'pwsh' });
  }
}

async function copyIgnoreFiles(files: string[], transformPathFunc: (path: string) => string) {
  for await (const filePath of files) {
    const outputFilePath = transformPathFunc(filePath);
    const outputDirPath = path.dirname(outputFilePath);
    await fs.mkdir(outputDirPath, { recursive: true });
    await fs.copyFile(filePath, outputFilePath);
  }
}


main();
